package com.cs.study.homework._0314.stack;


import java.sql.SQLInvalidAuthorizationSpecException;

// 栈的顺序存储--->底层使用数组
public class MyArrayStack<E> {
    private static int INIT_CAPACITY = 5;
    private Object[] values;
    private int size;

    public MyArrayStack() {
        values = new Object[INIT_CAPACITY];
    }

    public int size() {
        return size;
    }

    public boolean isEmpty() {
        return size == 0;
    }

    public boolean isFull() {
        return size == values.length;
    }


    //入栈
    public boolean push(E value) {
        if (isFull()) {
            grow();
        }
        values[size] = value;
        size++;
        return true;
    }

    public void grow() {
        Object[] newArray = new Object[values.length << 1];
        System.arraycopy(values, 0, newArray, 0, values.length);
        values = newArray;
    }

    //出栈
    public E pop() {
        if (isEmpty()) {
            throw new RuntimeException("stack is empty");
        }
        E value = (E) values[size - 1];
        values[size - 1] = null;
        size--;
        return value;
    }

    //返回栈顶元素
    public E peek() {
        // 判断栈空
        if (isEmpty()) {
            throw new RuntimeException("stack is empty!");
        }
        return (E) values[size - 1];
    }
}
